package com.sywb.chuangyebao.contract;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.aliyun.vodplayer.media.IAliyunVodPlayer;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.adapter.ScrollSpeedLinearLayoutManger;
import com.sywb.chuangyebao.adapter.SuperRecyclerAdapter;
import com.sywb.chuangyebao.bean.SuperInfo;
import com.sywb.chuangyebao.bean.VideoData;
import com.sywb.chuangyebao.library.player.AliPlayerView;
import com.sywb.chuangyebao.library.player.IVideoController;
import com.sywb.chuangyebao.library.player.listener.OnPlayerListener;
import com.sywb.chuangyebao.utils.DateTimeUtils;
import com.sywb.chuangyebao.utils.GlideUtils;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.utils.RegexUtils;
import com.sywb.chuangyebao.utils.ScreenSwitchUtils;
import com.sywb.chuangyebao.utils.Utils;
import com.sywb.chuangyebao.utils.WindowUtil;
import com.sywb.chuangyebao.view.VideoDetailActivity;
import com.sywb.chuangyebao.view.dialog.ShareDialog;

import org.bining.footstone.adapter.BaseRecyclerHolder;
import org.bining.footstone.adapter.listener.OnItemClickListener;
import org.bining.footstone.adapter.listener.OnItemLongClickListener;
import org.bining.footstone.adapter.listener.OnLoadMoreListener;
import org.bining.footstone.log.Logger;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

public interface VideoContract {

    interface View extends BaseRefreshContract.View {

        int getUId();

        boolean getVisibleToTab();

        boolean getVisibleToUser();
    }

    class Presenter extends BaseRefreshContract.Presenter<View> {

        protected VideoAdapter recyclerAdapter;

        //是否处于滚动状态
        private boolean mScrollState = false;

        // item 相关位置信息
        private int lastItemPosition = 0;// 可见的第一个Item位置
        private int firstItemPosition = 0;// 可见的最后一个Item位置
        private int visibleItemCount = 0;// 可见的Item个数

        private int itemPosition = 0;// item 的位置

        private int playerPosition = -1;// 正在播放item的位置
        private VideoHolder playViewHolder;

        private long currentPosition = 0;// 播放进度

        private ScreenSwitchUtils instance;
        private boolean isFullScreen;//是否处于全屏状态

        private int uId;
        private int pageNumber = 1;

        @Override
        public void onStart() {
            super.onStart();
            uId = mView.getUId();

            recyclerAdapter = new VideoAdapter(mActivity, uId);
            recyclerAdapter.setLoadingView(R.layout.layout_loading);
            recyclerAdapter.setPageSize(Constants.PAGESIZE);
            recyclerAdapter.setLoadMoreEnable(true);
            recyclerAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
                @Override
                public void onLoadMoreClick() {
                    onStartLoadMore();
                }
            });
            recyclerAdapter.setVideoHolderCallback(new MyVideoHolderCallback());
            recyclerAdapter.setPageSize(1);

            commonRecycler.addOnScrollListener(new MyScrollListener());
            commonRecycler.setLayoutManager(new ScrollSpeedLinearLayoutManger(mActivity));
            commonRecycler.setAdapter(recyclerAdapter);

            // setRecyclerAdapter(recyclerAdapter);

            if (uId > 0 && uId != 1234567) {
                pullToRefreshView.setRefreshEnable(false);
            }

            instance = ScreenSwitchUtils.init(mContext.getApplicationContext());

            initData();
        }

        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            try {
                int videoId = data.getIntExtra("p0", 0);
                int postion = data.getIntExtra("p1", 0);
                currentPosition = data.getLongExtra("p2", 0L);
                Logger.e("onActivityResult videoId：" + videoId + " postion：" + postion + " currentPosition：" + currentPosition);

                if (playerPosition == postion) {
                    VideoData videoData = recyclerAdapter.getItem(postion);
                    if (videoData.item_id == videoId) {
                        autoResume();
                        if (!autoResume()) {
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    autoResume();
                                }
                            }, 1000);
                        }
                        return;
                    }
                }
                currentPosition = 0L;
            } catch (Exception e) {
            }
        }

        public void onConfigurationChanged(Configuration newConfig) {
            if (mView == null || !mView.getVisibleToTab() || !mView.getVisibleToUser()) {
                return;
            }
            RxBus.get().post(Constants.ISFULLSCREEN, String.valueOf(newConfig.orientation));
            boolean orientation = newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE;//屏幕方向是否为横屏
            Logger.e("屏幕方向改变！！！是否为横屏：" + orientation);
            if (playViewHolder == null) {
                return;
            }
            AliPlayerView aliPlayerView = playViewHolder.getLlVideo();
            aliPlayerView.onConfigurationChanged(newConfig);
            if (orientation) {// 横屏
                if (mActivity == null) return;
                Activity activity = WindowUtil.scanForActivity(mActivity);
                if (activity == null) return;
                WindowUtil.hideSystemBar(mActivity);
                if (isFullScreen) return;
                playViewHolder.removeView();
                ViewGroup contentView = activity.findViewById(android.R.id.content);
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                contentView.addView(aliPlayerView, params);
                isFullScreen = true;
            } else {// 竖屏
                if (mActivity == null) return;
                Activity activity = WindowUtil.scanForActivity(mActivity);
                if (activity == null) return;
                if (!isFullScreen) return;
                WindowUtil.showSystemBar(mActivity);
                ViewGroup contentView = activity.findViewById(android.R.id.content);
                contentView.removeView(aliPlayerView);
                playViewHolder.addView();
                isFullScreen = false;
            }
        }

        class MyVideoHolderCallback implements OnVideoHolderCallback {

            @Override
            public void onStarted(VideoHolder videoHolder, int position) {
                Logger.e("MyVideoHolderCallback:" + position);
                if (playerPosition != position) {
                    stopPlayer(playerPosition);
                }
                playerPosition = position;
                playViewHolder = videoHolder;
                if (currentPosition > 0) {
                    playViewHolder.seekTo((int) currentPosition);
                    currentPosition = 0L;
                }
                if (mActivity != null) {
                    instance.start(mActivity);
                }
            }

            @Override
            public void onPaused(int position) {
                if (position == playerPosition) {
                    instance.stop();
                }
            }

            @Override
            public void onCompletion(int position) {
                if (position == playerPosition) {
                    instance.stop();
                }
                playerNext();
            }

            @Override
            public void onError(int position, int causeCode, int sceneCode, String message) {
                if (position == playerPosition) {
                    instance.stop();
                }
            }

            @Override
            public void onClickScreenDirection(int position, long currentPosition) {
                instance.toggleScreen();
                // VideoData videoInfo = recyclerAdapter.getDatas().get(position);
                // mView.advanceForResult(VideoDetailActivity.class, 10000, videoInfo.item_id, position, currentPosition, true);
            }

            /**
             * 去个人主页
             */
            @Override
            public void intentUser(int position) {
                VideoData videoInfo = recyclerAdapter.getDatas().get(position);
//                mView.advance(UserIndexActivity.class, videoInfo.owner.uid);
                Utils.goUserIndex(mView, videoInfo.owner.uid);
            }

            /**
             * 点赞
             */
            @Override
            public void intentPraise(int position) {
                if (!Utils.checkIsLogin()) {
                    return;
                }
                VideoData videoInfo = recyclerAdapter.getDatas().get(position);
                HttpUtils.agree(Constants.TOPIC_TYPE_VIDEO, videoInfo.item_id, !videoInfo.is_thumb, new HttpCallback<Object>(position) {
                    @Override
                    public void onSuccess(Object o) {
                        int postion = (int) data;

                        VideoData videoInfo = recyclerAdapter.getItem(postion);
                        videoInfo.is_thumb = !videoInfo.is_thumb;
                        int count = 0;
                        if (videoInfo.count != null) {
                            if (videoInfo.is_thumb) {
                                videoInfo.count.thumb_up += 1;
                            } else {
                                videoInfo.count.thumb_up -= 1;
                            }
                            count = videoInfo.count.thumb_up;
                        } else {
                            if (videoInfo.is_thumb) {
                                count = 1;
                            } else {
                                count = 0;
                            }
                        }

                        VideoHolder childViewHolder = (VideoHolder) commonRecycler.findViewHolderForAdapterPosition(postion);
                        if (childViewHolder != null) {
                            // 注册监听以及隐藏蒙层
                            childViewHolder.setIsThumb(videoInfo.is_thumb, count);
                        }
                    }

                    @Override
                    public void onError(String strMsg) {
                        super.onError(strMsg);
                        ToastUtils.show(mActivity, strMsg);
                    }
                });
            }

            /**
             * 评论
             */
            @Override
            public void intentComment(int position) {
                VideoData videoInfo = recyclerAdapter.getDatas().get(position);
                long currentPosition = 0L;
                VideoHolder childViewHolder = (VideoHolder) commonRecycler.findViewHolderForAdapterPosition(position);
                if (childViewHolder != null) {
                    currentPosition = childViewHolder.getCurPosition();
                }
                mView.advanceForResult(VideoDetailActivity.class, 10000, videoInfo.item_id, position, currentPosition);
            }

            /**
             * 分享
             */
            @Override
            public void intentShare(int position) {
                VideoData videoInfo = recyclerAdapter.getItem(position);
                if (videoInfo != null) {
                    ShareDialog sharedDialog = ShareDialog.newInstance(Constants.TOPIC_TYPE_VIDEO, videoInfo.item_id, ShareDialog.TYPE_REPORT, videoInfo.title, videoInfo.description, videoInfo.logo);
                    sharedDialog.show(mView.getMyFragmentManager(), "Shared");
                }
            }
        }

        /**
         * 列表的滚动监听
         */
        private class MyScrollListener extends RecyclerView.OnScrollListener {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                Logger.e("onScrollStateChanged");
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_DRAGGING:// 用户用手指滚动
                        mScrollState = true;
                        break;
                    case RecyclerView.SCROLL_STATE_SETTLING:// 自动滚动
                        mScrollState = true;
                        break;
                    case RecyclerView.SCROLL_STATE_IDLE:// 停止滑动
                        mScrollState = false;
                        //滑动停止和松开手指时，调用此方法 进行播放
                        if (playerPosition != itemPosition) {
                            if (playerPosition >= firstItemPosition && playerPosition <= lastItemPosition) {
                                if (getVisibilityPercents(recyclerView, playerPosition - firstItemPosition) < 95) {
                                    startPlayer(itemPosition);
                                }
                            } else {
                                startPlayer(itemPosition);
                            }
                        }
                        break;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Logger.e("onScrolled");
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                if (layoutManager instanceof LinearLayoutManager) {
                    LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                    // 获取第一个可见view的位置
                    firstItemPosition = linearManager.findFirstVisibleItemPosition();
                    //  获取最后一个可见view的位置
                    lastItemPosition = linearManager.findLastVisibleItemPosition();
                    // 获取可见view的总数
                    visibleItemCount = linearManager.getChildCount();

                    Logger.e("firstItemPosition:" + firstItemPosition + " lastItemPosition:" + lastItemPosition + " visibleItemCount:" + visibleItemCount);

                    if (mScrollState) {// 滚动
                        srcollVisible(recyclerView, firstItemPosition, lastItemPosition, visibleItemCount);
                    }

                    // Activity 中自动播放第一个
                    else { // 停止 进入时调用此方法，进行播放第一个
                        if (playerPosition == -1) {
                            startPlayer(itemPosition);
                            playerPosition = itemPosition;
                        }
                    }
                }
            }
        }

        /**
         * 滚动时 判断哪个view 显示百分比最大，哪个最大 视图亮起
         */
        private void srcollVisible(RecyclerView recyclerView, int firstItemPosition, int lastItemPosition, int visibleItemCount) {
            int position = 0; // 最大显示百分比的屏幕内的子view的位置
            for (int i = 0; i < visibleItemCount; i++) {
                if (getVisibilityPercents(recyclerView, i) >= 95) {
                    position = i;
                    break;
                }
            }
            itemPosition = (firstItemPosition + position);
            Logger.e("itemPosition:" + itemPosition + " playerPosition:" + playerPosition + " firstItemPosition:" + firstItemPosition + " lastItemPosition:" + lastItemPosition + " visibleItemCount:" + visibleItemCount);
            if (playerPosition != itemPosition && playerPosition >= 0) {
                if (playerPosition >= firstItemPosition && playerPosition <= lastItemPosition) {
                    if (getVisibilityPercents(recyclerView, playerPosition - firstItemPosition) < 95) {
                        stopPlayer(playerPosition);
                    }
                } else {
                    stopPlayer(playerPosition);
                }
            }
        }

        /**
         * 获取指定位置的Item的可见百分比
         */
        private int getVisibilityPercents(RecyclerView recyclerView, int position) {
            int visibilityPercents = 0;
            if (recyclerView != null) {
                android.view.View childAt = recyclerView.getChildAt(position).findViewById(R.id.ll_container);

                if (childAt == null) {
                    return visibilityPercents;
                }

                Rect mCurrentViewRect = new Rect();

                childAt.getLocalVisibleRect(mCurrentViewRect);

                int height = childAt.getHeight();
                int top = mCurrentViewRect.top;
                int bottom = mCurrentViewRect.bottom;

                if (top >= 0) {
                    visibilityPercents = (bottom - top) * 100 / height;
                } else if (bottom < 0) {
                    visibilityPercents = 0;
                }
            }
            return visibilityPercents;
        }

        /**
         * 添加播放器并开始播放视频，并获取之前的播放进度
         */
        public boolean startPlayer(int position) {
            Logger.e("startPlayer " + position);
            if (mView != null && mView.getVisibleToUser() && mView.getVisibleToTab() && position >= 0) {
                VideoHolder childViewHolder = (VideoHolder) commonRecycler.findViewHolderForAdapterPosition(position);
                if (childViewHolder != null) {
                    // 注册监听以及隐藏蒙层
                    childViewHolder.start();
                    playerPosition = position;
                    playViewHolder = childViewHolder;
                    return true;
                } else {
                    Logger.e("startPlayer 未取到对应位置的VideoHolder：" + position);
                }
            }
            return false;
        }

        /**
         * 停止播放视频
         */
        public void stopPlayer(int position) {
            Logger.e("stopPlayer " + position);
            if (position >= 0) {
                VideoHolder childViewHolder = (VideoHolder) commonRecycler.findViewHolderForAdapterPosition(position);
                if (childViewHolder != null) {
                    childViewHolder.pause();
                } else {
                    Logger.e("stopPlayer 未取到对应位置的VideoHolder：" + position);
                    if (playViewHolder != null) {
                        playViewHolder.pause();
                    }
                }
            }
        }

        /**
         * 视频播放完成自动滚动到下个视频
         */
        public void playerNext() {
            if (playerPosition >= 0 && playerPosition < (recyclerAdapter.getDataCount() - 1)) {
                commonRecycler.smoothScrollToPosition(playerPosition + 1);
            }
        }

        public void inspectPlayer() {
            Logger.e("inspectPlayer " + playerPosition);
            if (playerPosition >= 0) {
                VideoHolder childViewHolder = (VideoHolder) commonRecycler.findViewHolderForAdapterPosition(playerPosition);
                if (childViewHolder != null) {
                    childViewHolder.inspectPlayer();
                } else {
                    Logger.e("inspectPlayer 未取到对应位置的VideoHolder：" + playerPosition);
                    if (playViewHolder != null) {
                        playViewHolder.inspectPlayer();
                    }
                }
            }
        }

        public boolean autoResume() {
            Logger.e("autoResume " + playerPosition);
            if (mView != null && mView.getVisibleToUser() && mView.getVisibleToTab() && playerPosition >= 0) {
                VideoHolder childViewHolder = (VideoHolder) commonRecycler.findViewHolderForAdapterPosition(playerPosition);
                if (childViewHolder != null) {
                    childViewHolder.autoResume();
                    playViewHolder = childViewHolder;
                    return true;
                } else {
                    Logger.e("autoResume 未取到对应位置的VideoHolder：" + playerPosition);
                    if (playViewHolder != null) {
                        playViewHolder.autoResume();
                    }
                }
            }
            return false;
        }

        public void autoPause() {
            Logger.e("autoPause " + playerPosition);
            if (playerPosition >= 0) {
                instance.stop();
                VideoHolder childViewHolder = (VideoHolder) commonRecycler.findViewHolderForAdapterPosition(playerPosition);
                if (childViewHolder != null) {
                    childViewHolder.autoPause();
                } else {
                    Logger.e("autoPause 未取到对应位置的VideoHolder：" + playerPosition);
                    if (playViewHolder != null) {
                        playViewHolder.autoPause();
                    }
                }
            }
        }

        public void setUserVisibleHint() {
            if (commonRecycler != null && commonRecycler.getChildCount() > 0) {
                if (playerPosition < 0) {
                    startPlayer(itemPosition);
                } else {
                    if (mView != null && mView.getVisibleToUser() && mView.getVisibleToTab()) {
                        autoResume();
                    } else {
                        autoPause();
                    }
                }
            }
        }

        @Override
        public void onDestroy() {
            if (recyclerAdapter != null) {
                for (int i = 0; i < recyclerAdapter.getDataCount(); i++) {
                    VideoHolder childViewHolder = (VideoHolder) commonRecycler.findViewHolderForAdapterPosition(i);
                    if (childViewHolder != null) {
                        childViewHolder.destroy();
                    }
                }
            }
            super.onDestroy();
        }

        @Override
        public void initData() {
            onStartAsync();
            getVideoList();
        }

        @Override
        public void onStartRefresh() {
            stopPlayer(playerPosition);
            pageNumber = 1;
            getVideoList();
        }

        @Override
        public void onStartLoadMore() {
            pageNumber++;
            getVideoList();
        }

        private void getVideoList() {
            HttpUtils.getContentList(Constants.TOPIC_TYPE_VIDEO, uId < 0 ? null : String.valueOf(uId), null, pageNumber, null, "1", "1", new HttpCallback<List<SuperInfo>>() {
                @Override
                public void onSuccess(List<SuperInfo> superInfos) {
                    List<VideoData> videoDataList = new ArrayList<>();
                    if (superInfos != null) {
                        for (SuperInfo superInfo : superInfos) {
                            VideoData videoData = JSON.parseObject(superInfo.content, VideoData.class);
                            videoDataList.add(videoData);
                        }
                    }
                    if (pageNumber == 1) {
                        onEndRefresh();
//                        if (videoDataList.size() > 0) {
//                            recyclerAdapter.setFooterView(R.layout.layout_footer);
//                        } else {
//                            recyclerAdapter.setFooterView(null);
//                        }
                        if (recyclerAdapter.getDataCount() > 0) {
                            List<VideoData> oldDatas = recyclerAdapter.getDatas();
                            videoDataList.addAll(oldDatas);
                        }
                        recyclerAdapter.clearDatas();
                        playerPosition = 0;
//                        recyclerAdapter.setDatas(videoDataList);
                    }
                    recyclerAdapter.notifyDataChangedAfterLoadMore(videoDataList);
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    if (pageNumber == 1) {
                        onEndRefresh();
                    } else {
                        onEndLoadMore();
                    }
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                    isNoData();
                }
            });
        }

        @Override
        public void isNoData() {
            Logger.e("isNoData");
            boolean isNoData = recyclerAdapter.getDataCount() == 0;
            if (!isNoData && pageNumber == 1 && playerPosition >= 0) {
                Logger.e("isNoData startPlayer " + playerPosition);
                if (!startPlayer(playerPosition)) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            startPlayer(playerPosition);
                        }
                    }, 1000);
                }
            }
            if (mView != null) {
                mView.setNoData(isNoData);
            }
        }
    }

    class VideoHolder extends BaseRecyclerHolder implements android.view.View.OnClickListener, IVideoController {

        public AliPlayerView llVideo;

        public FrameLayout llContainer;

        public TextView tvTitle;
        public TextView tvWatchCount;
        public LinearLayout llTitle;

        public RelativeLayout rlAvatar;
        public ImageView ivAvatar;
        public ImageView ivTutorLabel;

        public TextView tvAuthor;
        public TextView tvPraise;
        public TextView tvComment;
        public ImageView ivShare;

        private Activity activity;
        private int videoUid;

        private int postion;
        protected boolean isFullScreen;//是否处于全屏状态

        private OnVideoHolderCallback listener;

        public VideoHolder(Activity activity, android.view.View itemView, OnItemClickListener onItemClickListener, OnItemLongClickListener onItemLongClickListener) {
            super(itemView, onItemClickListener, onItemLongClickListener);
            this.activity = activity;
        }

        public void initView() {

            this.llContainer = itemView.findViewById(R.id.ll_container);
            this.llTitle = itemView.findViewById(R.id.ll_title);
            this.tvTitle = itemView.findViewById(R.id.tv_title);
            this.tvWatchCount = itemView.findViewById(R.id.tv_watch_count);
            this.rlAvatar = itemView.findViewById(R.id.rl_avatar);
            this.ivAvatar = itemView.findViewById(R.id.iv_avatar);
            this.ivTutorLabel = itemView.findViewById(R.id.iv_tutor_label);
            this.tvAuthor = itemView.findViewById(R.id.tv_author);
            this.tvPraise = itemView.findViewById(R.id.tv_praise);
            this.tvComment = itemView.findViewById(R.id.tv_comment);
            this.ivShare = itemView.findViewById(R.id.iv_share);

            ivAvatar.setOnClickListener(this);
            tvAuthor.setOnClickListener(this);
            tvPraise.setOnClickListener(this);
            tvComment.setOnClickListener(this);
            ivShare.setOnClickListener(this);

            llContainer.removeAllViews();

            ViewGroup.LayoutParams layoutParams = llContainer.getLayoutParams();
            layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            layoutParams.height = (int) (org.bining.footstone.utils.ScreenUtils.getScreenWidth() * 0.56F);
            llContainer.setLayoutParams(layoutParams);

            if (llVideo != null) {
                llVideo.destroy();
            }

            llVideo = new AliPlayerView(mContext);
            llVideo.setOnPlayerListener(new OnPlayerListener() {
                @Override
                public void onInit() {
                    showAvatar();
                }

                @Override
                public void onPrepared() {
                    hideAvatar();
                }

                @Override
                public void onStarted() {
                    hideAvatar();
                    if (listener != null) {
                        listener.onStarted(VideoHolder.this, postion);
                    }
                }

                @Override
                public void onPaused() {
                    hideAvatar();
                    if (listener != null) {
                        listener.onPaused(postion);
                    }
                }

                @Override
                public void onCompletion() {
                    hideAvatar();
                    if (listener != null) {
                        if (isFullScreen) {
                            listener.onClickScreenDirection(postion, llVideo.getAliyunVodPlayer().getCurrentPosition());
                        } else {
                            listener.onCompletion(postion);
                        }
                    }
                }

                @Override
                public void onError(int causeCode, int sceneCode, String message) {
                    hideAvatar();
                    if (listener != null) {
                        listener.onError(postion, causeCode, sceneCode, message);
                    }
                }

                @Override
                public void onShare(int platformType) {
                    if (listener != null) {
                        listener.intentShare(postion);
                    }
                }

                @Override
                public void onClickScreenDirection() {
                    if (listener != null) {
                        listener.onClickScreenDirection(postion, llVideo.getAliyunVodPlayer().getCurrentPosition());
                    }
                }

                @Override
                public void showToolsView() {
                    llTitle.setVisibility(android.view.View.VISIBLE);
                }

                @Override
                public void hideToolsView() {
                    llTitle.setVisibility(android.view.View.GONE);
                }

                @Override
                public void updateProgress(int curPosition, int bufferPosition, int duration) {
                }
            });

            addView();
        }

        public void setVideoUid(int videoUid) {
            this.videoUid = videoUid;
        }

        /**
         * 初始化值
         */
        public void setItemData(int postion, VideoData videoInfo) {
            initView();

            this.postion = postion;

            Logger.e("setItemData:" + postion);

            tvTitle.setText(videoInfo.title);
            tvWatchCount.setText(videoInfo.count.getPlayTimesTotal());

            if (videoUid == 1234567) {
                tvAuthor.setVisibility(android.view.View.GONE);
                rlAvatar.setVisibility(android.view.View.GONE);
            } else {
                tvAuthor.setVisibility(android.view.View.VISIBLE);
                rlAvatar.setVisibility(android.view.View.VISIBLE);
            }
            GlideUtils.getCircleImageToUrl(activity, videoInfo.owner.getShowAvatar(), ivAvatar, R.drawable.head_image);
            Utils.setUserRoleIcon(ivTutorLabel, videoInfo.owner.user_role);
            tvAuthor.setText(videoInfo.owner.getShowName());

            setIsThumb(videoInfo.is_thumb, videoInfo.count.thumb_up);

            if (videoInfo.count.comment > 0) {
                tvComment.setText(RegexUtils.getFormatNum(videoInfo.count.comment));
            } else {
                tvComment.setText("评论");
            }

            init(activity, IVideoController.MODE_VIDEO, videoInfo.url, videoInfo.logo, DateTimeUtils.getMediaTimeNumber(videoInfo.length));
        }

        public void setIsThumb(boolean isThumb, int thumbCount) {
            Drawable drawable;
            if (isThumb) {
                drawable = activity.getResources().getDrawable(R.drawable.praise_fill);
            } else {
                drawable = activity.getResources().getDrawable(R.drawable.praise);
            }
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tvPraise.setCompoundDrawables(drawable, null, null, null);
            tvPraise.setText(thumbCount > 0 ? RegexUtils.getFormatNum(thumbCount) : "点赞");
        }

        public void showAvatar() {
            llTitle.setVisibility(android.view.View.VISIBLE);
            if (videoUid != 1234567) {
                rlAvatar.setVisibility(android.view.View.VISIBLE);
            }
        }

        public void hideAvatar() {
            llTitle.setVisibility(android.view.View.GONE);
            if (videoUid != 1234567) {
                rlAvatar.setVisibility(android.view.View.GONE);
            }
        }

        @Override
        public void onClick(android.view.View v) {
            switch (v.getId()) {
                case R.id.iv_avatar:
                    if (listener != null) {
                        listener.intentUser(postion);
                    }
                    break;
                case R.id.tv_author:
                    if (listener != null) {
                        listener.intentUser(postion);
                    }
                    break;
                case R.id.tv_praise:
                    if (listener != null) {
                        listener.intentPraise(postion);
                    }
                    break;
                case R.id.tv_comment:
                    if (listener != null) {
                        listener.intentComment(postion);
                    }
                    break;
                case R.id.iv_share:
                    if (listener != null) {
                        listener.intentShare(postion);
                    }
                    break;
            }
        }

        /**
         * 注册监听
         */
        public void setVideoHolderCallback(OnVideoHolderCallback listener) {
            this.listener = listener;
        }

        /**
         * 解除监听
         */
        public void unRegisterVideoPlayerListener() {
            if (listener != null) {
                listener = null;
            }
        }

        public void addView() {
            isFullScreen = false;
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            llContainer.removeAllViews();
            llContainer.addView(llVideo, params);
        }

        public void removeView() {
            isFullScreen = true;
            llContainer.removeView(llVideo);
        }

        public AliPlayerView getLlVideo() {
            return llVideo;
        }

        public long getCurPosition() {
            return llVideo.getAliyunVodPlayer().getCurrentPosition();
        }

        @Override
        public void init(int mode) {
        }

        @Override
        public void init(Activity mActivity, int mode, String playUrl, String previewPath, String duration) {
            llVideo.init(mActivity, mode, playUrl, previewPath, duration);
        }

        @Override
        public void start() {
            if (llVideo.getPlayerState() != IAliyunVodPlayer.PlayerState.Error) {
                llVideo.start();
            }
        }

        @Override
        public void start(Activity mActivity, String playUrl, String previewPath, String duration) {
        }

        @Override
        public void pause() {
            llVideo.pause();
        }

        @Override
        public void autoPause() {
            llVideo.autoPause();
        }

        @Override
        public void resume() {
            llVideo.resume();
        }

        @Override
        public void autoResume() {
            llVideo.autoResume();
        }

        @Override
        public void stop() {

        }

        @Override
        public void destroy() {
            llVideo.destroy();
        }

        @Override
        public void seekTo(int ms) {
            llVideo.seekTo(ms);
        }

        @Override
        public void setCanReplay(boolean isCanReplay) {
            llVideo.setCanReplay(isCanReplay);
        }

        @Override
        public void error(int causeCode, int sceneCode, String message) {
            llVideo.error(causeCode, sceneCode, message);
        }

        @Override
        public void showToolsView() {
            llVideo.showToolsView();
        }

        @Override
        public void showToolsView(int time) {
            llVideo.showToolsView(time);
        }

        @Override
        public void hideToolsView() {
            llVideo.hideToolsView();
        }

        @Override
        public void updateProgress(int curPosition, int bufferPosition, int duration) {
            llVideo.updateProgress(curPosition, bufferPosition, duration);
        }

        @Override
        public void changedConfiguration() {
            llVideo.changedConfiguration();
        }

        @Override
        public boolean inspectPlayer() {
            return llVideo.inspectPlayer();
        }

        @Override
        public boolean isCanPlayer() {
            return false;
        }

    }

    class VideoAdapter extends SuperRecyclerAdapter<VideoData, VideoHolder> {

        private Activity activity;
        private int videoUid;

        private OnVideoHolderCallback onVideoHolderCallback;

        public VideoAdapter(Activity activity, int videoUid) {
            super(activity, R.layout.item_video);
            this.activity = activity;
            this.videoUid = videoUid;
        }

        @Override
        protected VideoHolder onCreateViewHolder(ViewGroup parent, android.view.View itemView) {
            VideoHolder viewHolder = new VideoHolder(activity, itemView, mOnItemClickListener, mOnItemLongClickListener);
            viewHolder.setVideoUid(videoUid);
            viewHolder.setVideoHolderCallback(onVideoHolderCallback);
            viewHolder.getViewHolderHelper().setOnItemChildClickListener(mOnItemChildClickListener);
            viewHolder.getViewHolderHelper().setOnItemChildLongClickListener(mOnItemChildLongClickListener);
            return viewHolder;
        }

        @Override
        protected int getDefItemViewType(int position) {
            if (position >= getDataCount()) {
                return 0x00000333;
            }
            return super.getDefItemViewType(position);
        }

        @Override
        protected void setItemData(VideoHolder viewHolder, int position, VideoData model) {
            viewHolder.setItemData(position, model);
        }

        public void setVideoHolderCallback(OnVideoHolderCallback onVideoHolderCallback) {
            this.onVideoHolderCallback = onVideoHolderCallback;
        }
    }

    /**
     * item 的点击事件
     */
    interface OnVideoHolderCallback {

        void onStarted(VideoHolder videoHolder, int position);

        void onPaused(int position);

        void onCompletion(int position);

        void onError(int position, int causeCode, int sceneCode, String message);

        void onClickScreenDirection(int position, long currentPosition);

        void intentUser(int position);

        void intentPraise(int position);

        void intentComment(int position);

        void intentShare(int position);
    }

}

